﻿using System.IO;
using System.Net;
using System.Xml;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections.Specialized;
using System.Web;
using System.Data.SqlClient;
using System.Reflection;
using System;
using Microsoft.SharePoint;

namespace CodeArt.SharePoint.MultiLanSupport
{    
    class MultiLanFilter : Stream
    {            
        private Stream _sink;
        private long _position;
        private string _Lang;
        //private StringBuilder responseHtml;
       
        private const string META = "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"/>";

        //ITranslator _trans = new CachedTranslator();
        ITranslator _trans ;

        const string Chinese_Lan = "Chs";
        const string English_Lan = "Eng";

        string _curLanKey;

       // bool _isSameLan = false;

        public MultiLanFilter(Stream sink)
        {
            _sink = sink;
            //responseHtml = new StringBuilder();

            SPContext spContext = SPContext.Current;

            //如果线程语言跟站点语言相同，则无需处理
            if (System.Threading.Thread.CurrentThread.CurrentUICulture.LCID
                == spContext.Web.Language)
            {
                //_isSameLan = true;
                _trans = new SameLanTranslator();
            }
            else
            {
                //
                //_trans = new NoCacheTranslator();//不使用缓存
                _trans = new CachedTranslator();  //使用缓存
            }

            string curLanCode = UICultureManager.CurrentInstance.CurrentUICultureName.ToLower();

            //对中英文使用更友好的code，其他语言直接采用语言code
            if (curLanCode == UICultureManager.English_Lan_Name)
                _curLanKey = English_Lan;
            else if (curLanCode == UICultureManager.Chinese_Lan_Name)
                _curLanKey = Chinese_Lan;
            else
                _curLanKey = curLanCode;

        }
        //New

        #region " Code that will most likely never change from filter to filter. "
        // The following members of Stream must be overridden.
        public override bool CanRead
        {
            get { return true; }
        }

        public override bool CanSeek
        {
            get { return true; }
        }

        public override bool CanWrite
        {
            get { return true; }
        }

        public override long Length
        {
            get { return 0; }
        }

        public override long Position
        {
            get { return _position; }
            set { _position = value; }
        }

        public override long Seek(long offset, System.IO.SeekOrigin direction)
        {
            return _sink.Seek(offset, direction);
        }
        //Seek

        public override void SetLength(long length)
        {
            _sink.SetLength(length);
        }
        //SetLength

        public override void Close()
        {
            _sink.Close();
        }
        //Close

        public override void Flush()
        {
            _sink.Flush();
        }
        //Flush

        public override int Read(byte[] MyBuffer, int offset, int count)
        {
           return _sink.Read(MyBuffer, offset, count);
        }

        public string Language
        {
            get
            {
                if (_Lang.Trim().Length == 0)
                {
                    return "en";
                }
                else
                {
                    return _Lang;
                }

                return _Lang;
            }
            set { _Lang = value; }
        }
        
        #endregion

        //private static Regex _reg = new Regex(@"\[\[.+?\]\]");

        private static Regex _reg = new Regex(@"\$.+?\$");

        private static char[] _trimedChars = new char[]{ '$' , '$' };

        public override void Write(byte[] Buffer, int offset, int count)
        {
            string sBuffer = System.Text.UTF8Encoding.UTF8.GetString(Buffer, offset, count);

            StringCollection tags = new StringCollection();

            //这个解析应该放到缓存中
            MatchCollection mc = _reg.Matches(sBuffer);
            foreach (Match m in mc)
            {
                tags.Add(m.Value.Trim());
            }

            bool transed = false;
            StringBuilder finalHtml = new StringBuilder ( sBuffer ) ;
                
            foreach (string s in tags)
            {
                string trans = _trans.Translate(s.Trim(_trimedChars), _curLanKey, out transed);
                if (transed)
                    finalHtml.Replace(s, trans);
            }           

            byte[] data = System.Text.UTF8Encoding.UTF8.GetBytes(finalHtml.ToString());

            _sink.Write(data, 0, data.Length);            
        }
        
        //private void SaveWord(string psFromText, string psToText)
        //{
        //    using (SqlConnection loConn = new SqlConnection(My.Settings.DictionaryConnection))
        //    {
        //        loConn.Open();


        //        using (SqlCommand loComm = new SqlCommand("DictionaryInsert", loConn))
        //        {
        //            loComm.CommandType = CommandType.StoredProcedure;
        //            loComm.Parameters.Add(new SqlParameter("@FromText", psFromText));
        //            loComm.Parameters.Add(new SqlParameter("@ToText", psToText));
        //            loComm.Parameters.Add(new SqlParameter("@Language", Language));
        //            loComm.Parameters.Add(new SqlParameter("@UserID", "Systran"));
        //            loComm.ExecuteNonQuery();
        //        }
        //        loConn.Close();
        //    }
        //}


    }
}